package com.dstz.bus.service.impl;

import java.util.Map.Entry;

import org.springframework.stereotype.Service;

import com.dstz.base.api.exception.BusinessError;
import com.dstz.base.core.util.AppUtil;
import com.dstz.bus.api.constant.BusStatusCode;
import com.dstz.bus.api.constant.BusinessObjectPersistenceType;
import com.dstz.bus.model.BusinessData;
import com.dstz.bus.model.BusinessObject;
import com.dstz.bus.service.BusinessDataPersistenceService;
import com.dstz.bus.service.IBusinessDataPersistenceBeanService;

/**
 * <pre>
 * 描述：servicBean方式持久化数据
 * 作者:aschs
 * 邮箱:aschs@qq.com
 * 日期:2019年7月22日
 * 版权:summer
 * </pre>
 */
@Service
public class BusinessDataPersistenceBeanService implements BusinessDataPersistenceService {

	@Override
	public String type() {
		return BusinessObjectPersistenceType.BEAN.getKey();
	}

	@Override
	public void saveData(BusinessData businessData) {
		BusinessObject businessObject = businessData.getBusTableRel().getBusObj();
		IBusinessDataPersistenceBeanService beanService = getBeanService(businessObject);
		beanService.saveData(businessData);
	}

	@Override
	public BusinessData loadData(BusinessObject businessObject, Object id) {
		IBusinessDataPersistenceBeanService beanService = getBeanService(businessObject);
		return beanService.loadData(businessObject, id);
	}

	@Override
	public void removeData(BusinessObject businessObject, Object id) {
		IBusinessDataPersistenceBeanService beanService = getBeanService(businessObject);
		beanService.removeData(businessObject, id);
	}

	private IBusinessDataPersistenceBeanService getBeanService(BusinessObject businessObject) {
		String name = businessObject.getPerTypeConfig();
		IBusinessDataPersistenceBeanService beanService = null;
		for (Entry<String, IBusinessDataPersistenceBeanService> entry : AppUtil.getImplInstance(IBusinessDataPersistenceBeanService.class).entrySet()) {
			if (entry.getValue().getName().equals(name)) {
				beanService = entry.getValue();
			}
		}
		if (beanService == null) {
			throw new BusinessError("找不到名字为【" + name + "】的bean", BusStatusCode.PERSISTENCE_BEAN_ERR);
		}
		return beanService;
	}
}
